package com.qf.bank.common.utils;

import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.InputStream;

/**
 * @author 惠佳旭
 * @date 2019/12/5
 */
public class QiniuUtils {

  private static String accessKey = "IbxH8bAD-o4AaCCfSx0Vi8taB1uSr2s6EYdLlV5q";
  private static String secretKey = "pQ16CSH7NUB5eI8j95YsKXZylROfDGhMVXOi6gAI";
  private static String bucket = "huijiaxv";
  public static String qiniuUrl = "http://q1v2zwotv.bkt.clouddn.com/";

  public static String uploadToQiniu(InputStream img) {
    // 华北服务器
    Configuration configuration = new Configuration(Region.huabei());
    Auth auth = Auth.create(accessKey, secretKey);
    String uploadToken = auth.uploadToken(bucket);
    // 默认不指定key的情况下，以文件内容的hash值作为文件名
    String key = null;
    try {
      UploadManager uploadManager = new UploadManager(configuration);
      Response response = uploadManager.put(img, key, uploadToken, null, null);
      DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
      return putRet.key;
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return null;
  }

  public static boolean deleteFromQiniu(String key) {
    // 华北服务器
    Configuration configuration = new Configuration(Region.huabei());
    Auth auth = Auth.create(accessKey, secretKey);
    BucketManager bucketManager = new BucketManager(auth, configuration);
    try {
      bucketManager.delete(bucket, key);
      return true;
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return false;
  }
}
